// packageA/pages/delivery-manager/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        currentTab: 'all',
        showSearchModal: false,
        showActionModal: false,
        searchKeyword: '',
        searchResults: [],
        selectedIndex: -1,
        hasMore: true,
        deliveryList: [
            {
                id: '100001910',
                name: '赵天艳',
                phone: '+8613612345678',
                workType: 'full',
                location: '广东省深圳市龙华区民治街道武治天虹附近',
                monthlyOrders: 0,
                score: 0,
                authStatus: 'uncertified',
                registerTime: '2009-06-28 11:55:26',
                status: 'inactive',
                selected: false
            },
            {
                id: '100001889',
                name: '钱文勇',
                phone: '+8613612345678',
                workType: 'part',
                location: '广东省深圳市龙华区民治街道武治天虹附近',
                monthlyOrders: 0,
                score: 0,
                authStatus: 'uncertified',
                registerTime: '2009-06-28 11:55:26',
                status: 'inactive',
                selected: false
            },
            {
                id: '100001784',
                name: '孙宇雷',
                phone: '+8613612345678',
                workType: 'full',
                location: '广东省深圳市龙华区民治街道武治天虹附近',
                monthlyOrders: 1175,
                score: 5.0,
                authStatus: 'certified',
                registerTime: '2009-06-28 11:55:26',
                status: 'working',
                selected: false
            },
            {
                id: '100001677',
                name: '李洪辉',
                phone: '+8613612345678',
                workType: 'part',
                location: '广东省深圳市龙华区民治街道武治天虹附近',
                monthlyOrders: 1328,
                score: 4.8,
                authStatus: 'certified',
                registerTime: '2009-06-28 11:55:26',
                status: 'locked',
                selected: false
            },
            {
                id: '100001589',
                name: '周日丹',
                phone: '+8613612345678',
                workType: 'full',
                location: '广东省深圳市龙华区民治街道武治天虹附近',
                monthlyOrders: 1167,
                score: 4.3,
                authStatus: 'certified',
                registerTime: '2009-06-28 11:55:26',
                status: 'resting',
                selected: false
            },
            {
                id: '100001453',
                name: '吴秋农',
                phone: '+8613612345678',
                workType: 'full',
                location: '广东省深圳市龙华区民治街道武治天虹附近',
                monthlyOrders: 1045,
                score: 4.6,
                authStatus: 'certified',
                registerTime: '2009-06-28 11:55:26',
                status: 'working',
                selected: false
            },
            {
                id: '100001984',
                name: '郭冬霞',
                phone: '+8613612345678',
                workType: 'full',
                location: '广东省深圳市龙华区民治街道武治天虹附近',
                monthlyOrders: 1359,
                score: 3.0,
                authStatus: 'certified',
                registerTime: '2009-06-28 11:55:26',
                status: 'resting',
                selected: false
            },
            {
                id: '100001283',
                name: '王云鹏',
                phone: '+8613612345678',
                workType: 'part',
                location: '广东省深圳市龙华区民治街道武治天虹附近',
                monthlyOrders: 1007,
                score: 4.9,
                authStatus: 'certified',
                registerTime: '2009-06-28 11:55:26',
                status: 'locked',
                selected: false
            },
            {
                id: '100001212',
                name: '冯金生',
                phone: '+8613612345678',
                workType: 'part',
                location: '广东省深圳市龙华区民治街道武治天虹附近',
                monthlyOrders: 908,
                score: 4.2,
                authStatus: 'certified',
                registerTime: '2009-06-28 11:55:26',
                status: 'resigned',
                selected: false
            }
        ]
    },

    // 切换标签页
    switchTab: function (e) {
        const tab = e.currentTarget.dataset.tab;
        this.setData({
            currentTab: tab
        });
        this.filterDeliveryList(tab);
    },
// 加载配送员数据（编辑模式）
loadDeliveryData: function(id) {
    // 模拟从服务器加载数据
    const mockData = {
      id: id,
      name: '赵天艳',
      phone: '13612345678',
      workType: '0', // 对应workTypeOptions的索引
      area: '0', // 对应areaOptions的索引
      location: '广东省深圳市龙华区民治街道武治天虹附近',
      idCard: '440301199001011234',
      idCardFront: 'https://example.com/id-front.jpg',
      idCardBack: 'https://example.com/id-back.jpg',
      status: 'active'
    };
    
    this.setData({
      formData: mockData
    });
  },
    // 根据状态筛选配送员列表
    filterDeliveryList: function (tab) {
        let filteredList = this.data.deliveryList;

        switch (tab) {
            case 'working':
                filteredList = filteredList.filter(item => item.status === 'working');
                break;
            case 'resting':
                filteredList = filteredList.filter(item => item.status === 'resting');
                break;
            case 'inactive':
                filteredList = filteredList.filter(item => item.status === 'inactive');
                break;
            default:
                // 全部显示
                break;
        }

        this.setData({
            deliveryList: filteredList
        });
    },
    // 添加配送员
    addDelivery: function () {
        wx.navigateTo({
            url: '/packageA/pages/delivery-edit/index'
        });
    },

    // 编辑配送员
    editDelivery: function (e) {
        const index = e.currentTarget.dataset.index;
        const delivery = this.data.deliveryList[index];
        wx.navigateTo({
            url: `/packageA/pages/delivery-edit/index?id=${delivery.id}`
        });
    },

    // 刷新数据
    onRefresh: function () {
        // 重新加载数据
        this.loadDeliveryData();
    },
    // 全选/取消全选
    toggleSelectAll: function () {
        const allSelected = this.data.deliveryList.every(item => item.selected);
        const newList = this.data.deliveryList.map(item => ({
            ...item,
            selected: !allSelected
        }));

        this.setData({
            deliveryList: newList
        });
    },

    // 单选
    toggleSelect: function (e) {
        const index = e.currentTarget.dataset.index;
        const newList = [...this.data.deliveryList];
        newList[index].selected = !newList[index].selected;

        this.setData({
            deliveryList: newList
        });
    },

    // 显示操作菜单
    showActions: function (e) {
        const index = e.currentTarget.dataset.index;
        this.setData({
            showModal: true,
            selectedIndex: index
        });
    },

    // 隐藏模态框
    hideModal: function () {
        this.setData({
            showModal: false,
            selectedIndex: -1
        });
    },

    // 编辑配送员
    // editDelivery: function () {
    //     const index = this.data.selectedIndex;
    //     const delivery = this.data.deliveryList[index];

    //     wx.showToast({
    //         title: `编辑 ${delivery.name}`,
    //         icon: 'none'
    //     });

    //     this.hideModal();
    // },

    // 锁定账号
    lockDelivery: function () {
        const index = this.data.selectedIndex;
        const delivery = this.data.deliveryList[index];

        wx.showModal({
            title: '确认锁定',
            content: `确定要锁定配送员 ${delivery.name} 的账号吗？`,
            success: (res) => {
                if (res.confirm) {
                    const newList = [...this.data.deliveryList];
                    newList[index].status = 'locked';

                    this.setData({
                        deliveryList: newList
                    });

                    wx.showToast({
                        title: '账号已锁定',
                        icon: 'success'
                    });
                }
            }
        });

        this.hideModal();
    },

    // 重置密码
    resetPassword: function () {
        const index = this.data.selectedIndex;
        const delivery = this.data.deliveryList[index];

        wx.showModal({
            title: '重置密码',
            content: `确定要为配送员 ${delivery.name} 重置密码吗？`,
            success: (res) => {
                if (res.confirm) {
                    wx.showToast({
                        title: '密码已重置',
                        icon: 'success'
                    });
                }
            }
        });

        this.hideModal();
    },

    // 删除配送员
    deleteDelivery: function () {
        const index = this.data.selectedIndex;
        const delivery = this.data.deliveryList[index];

        wx.showModal({
            title: '确认删除',
            content: `确定要删除配送员 ${delivery.name} 吗？此操作不可恢复。`,
            success: (res) => {
                if (res.confirm) {
                    const newList = [...this.data.deliveryList];
                    newList.splice(index, 1);

                    this.setData({
                        deliveryList: newList
                    });

                    wx.showToast({
                        title: '删除成功',
                        icon: 'success'
                    });
                }
            }
        });

        this.hideModal();
    },

    // 获取状态文本
    getStatusText: function (status) {
        const statusMap = {
            'working': '接单中',
            'resting': '休息中',
            'locked': '已锁定',
            'inactive': '未开通',
            'resigned': '已离职'
        };
        return statusMap[status] || '未知';
    },

    // onLoad: function (options) {
    //     // 页面加载时的初始化操作
    //     console.log('配送员管理页面加载');
    // },

    // onPullDownRefresh: function () {
    //     // 下拉刷新
    //     wx.stopPullDownRefresh();
    // },
    // 计算选中数量
    getSelectedCount() {
        const count = this.data.deliveryList.filter(item => item.selected).length;
        this.setData({ selectedCount: count });
    },

    // 切换标签页
    switchTab: function (e) {
        const tab = e.currentTarget.dataset.tab;
        this.setData({
            currentTab: tab
        });
        this.filterDeliveryList(tab);
    },

    // 筛选配送员列表
    filterDeliveryList: function (tab) {
        let filteredList = [...this.data.deliveryList]; // 实际开发中这里应该是从服务器获取数据

        switch (tab) {
            case 'working':
                filteredList = filteredList.filter(item => item.status === 'working');
                break;
            case 'resting':
                filteredList = filteredList.filter(item => item.status === 'resting');
                break;
            case 'inactive':
                filteredList = filteredList.filter(item => item.status === 'inactive');
                break;
            default:
                break;
        }

        this.setData({
            deliveryList: filteredList
        });
        this.getSelectedCount();
    },

    // 选择单个配送员
    toggleSelect: function (e) {
        const index = e.currentTarget.dataset.index;
        const newList = [...this.data.deliveryList];
        newList[index].selected = !newList[index].selected;

        this.setData({
            deliveryList: newList
        });
        this.getSelectedCount();
    },

    // 显示搜索模态框
    showSearch: function () {
        this.setData({
            showSearchModal: true,
            searchResults: this.data.deliveryList // 初始显示所有结果
        });
    },

    // 隐藏搜索模态框
    hideSearchModal: function () {
        this.setData({
            showSearchModal: false,
            searchKeyword: ''
        });
    },

    // 搜索输入
    onSearchInput: function (e) {
        const keyword = e.detail.value;
        this.setData({
            searchKeyword: keyword
        });

        if (!keyword.trim()) {
            this.setData({ searchResults: this.data.deliveryList });
            return;
        }

        const results = this.data.deliveryList.filter(item =>
            item.name.includes(keyword) ||
            item.id.includes(keyword) ||
            item.phone.includes(keyword)
        );

        this.setData({ searchResults: results });
    },

    // 清空搜索
    clearSearch: function () {
        this.setData({
            searchKeyword: '',
            searchResults: this.data.deliveryList
        });
    },

    // 选择搜索结果
    selectSearchResult: function (e) {
        const item = e.currentTarget.dataset.item;
        // 这里可以跳转到详情页或高亮显示
        wx.showToast({
            title: `选中: ${item.name}`,
            icon: 'none'
        });
        this.hideSearchModal();
    },

    // 显示卡片操作菜单
    showCardActions: function (e) {
        const index = e.currentTarget.dataset.index;
        this.setData({
            showActionModal: true,
            selectedIndex: index
        });
    },

    // 隐藏操作菜单
    hideActionModal: function () {
        this.setData({
            showActionModal: false,
            selectedIndex: -1
        });
    },

    // 快速操作函数
    // editDelivery: function (e) {
    //     const index = e.currentTarget.dataset.index;
    //     const delivery = this.data.deliveryList[index];
    //     this.editDeliveryAction(delivery);
    // },

    quickLock: function (e) {
        const index = e.currentTarget.dataset.index;
        this.lockDeliveryAction(index);
    },

    confirmDelete: function (e) {
        const index = e.currentTarget.dataset.index;
        this.deleteDeliveryAction(index);
    },

    // 模态框操作函数
    editDeliveryFromModal: function () {
        const index = this.data.selectedIndex;
        const delivery = this.data.deliveryList[index];
        this.editDeliveryAction(delivery);
        this.hideActionModal();
    },

    lockDeliveryFromModal: function () {
        const index = this.data.selectedIndex;
        this.lockDeliveryAction(index);
        this.hideActionModal();
    },

    resetPasswordFromModal: function () {
        const index = this.data.selectedIndex;
        this.resetPasswordAction(index);
        this.hideActionModal();
    },

    deleteDeliveryFromModal: function () {
        const index = this.data.selectedIndex;
        this.deleteDeliveryAction(index);
        this.hideActionModal();
    },

    // 具体操作实现
    editDeliveryAction: function (delivery) {
        wx.showToast({
            title: `编辑 ${delivery.name}`,
            icon: 'none'
        });
    },

    lockDeliveryAction: function (index) {
        const delivery = this.data.deliveryList[index];
        wx.showModal({
            title: '确认锁定',
            content: `确定要锁定配送员 ${delivery.name} 的账号吗？`,
            success: (res) => {
                if (res.confirm) {
                    const newList = [...this.data.deliveryList];
                    newList[index].status = 'locked';
                    this.setData({ deliveryList: newList });
                    wx.showToast({ title: '账号已锁定', icon: 'success' });
                }
            }
        });
    },

    resetPasswordAction: function (index) {
        const delivery = this.data.deliveryList[index];
        wx.showModal({
            title: '重置密码',
            content: `确定要为配送员 ${delivery.name} 重置密码吗？`,
            success: (res) => {
                if (res.confirm) {
                    wx.showToast({ title: '密码已重置', icon: 'success' });
                }
            }
        });
    },

    deleteDeliveryAction: function (index) {
        const delivery = this.data.deliveryList[index];
        wx.showModal({
            title: '确认删除',
            content: `确定要删除配送员 ${delivery.name} 吗？此操作不可恢复。`,
            success: (res) => {
                if (res.confirm) {
                    const newList = [...this.data.deliveryList];
                    newList.splice(index, 1);
                    this.setData({ deliveryList: newList });
                    this.getSelectedCount();
                    wx.showToast({ title: '删除成功', icon: 'success' });
                }
            }
        });
    },

    // 批量操作
    batchLock: function () {
        const selectedItems = this.data.deliveryList.filter(item => item.selected);
        if (selectedItems.length === 0) return;

        wx.showModal({
            title: '批量锁定',
            content: `确定要锁定选中的 ${selectedItems.length} 个账号吗？`,
            success: (res) => {
                if (res.confirm) {
                    const newList = this.data.deliveryList.map(item =>
                        item.selected ? { ...item, status: 'locked', selected: false } : item
                    );
                    this.setData({ deliveryList: newList });
                    this.getSelectedCount();
                    wx.showToast({ title: '批量锁定成功', icon: 'success' });
                }
            }
        });
    },

    batchDelete: function () {
        const selectedItems = this.data.deliveryList.filter(item => item.selected);
        if (selectedItems.length === 0) return;

        wx.showModal({
            title: '批量删除',
            content: `确定要删除选中的 ${selectedItems.length} 个配送员吗？`,
            success: (res) => {
                if (res.confirm) {
                    const newList = this.data.deliveryList.filter(item => !item.selected);
                    this.setData({ deliveryList: newList });
                    this.getSelectedCount();
                    wx.showToast({ title: '批量删除成功', icon: 'success' });
                }
            }
        });
    },

    // 获取状态文本
    getStatusText: function (status) {
        const statusMap = {
            'working': '接单中',
            'resting': '休息中',
            'locked': '已锁定',
            'inactive': '未开通',
            'resigned': '已离职'
        };
        return statusMap[status] || '未知';
    },

    // 加载更多
    loadMore: function () {
        wx.showLoading({ title: '加载中' });
        setTimeout(() => {
            // 模拟加载更多数据
            wx.hideLoading();
            wx.showToast({ title: '没有更多数据了', icon: 'none' });
            this.setData({ hasMore: false });
        }, 1000);
    },

    onLoad: function (options) {
        this.getSelectedCount();
    },

    onPullDownRefresh: function () {
        setTimeout(() => {
            wx.stopPullDownRefresh();
            wx.showToast({ title: '刷新成功', icon: 'success' });
        }, 1000);
    },
    /**
     * 生命周期函数--监听页面加载
     */
    // onLoad(options) {

    // },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    // onPullDownRefresh() {

    // },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})